// import { fileURLToPath } from 'url'
import { join } from 'path'
import fs from 'fs'
import { createServer } from 'http'
// import appConfig from '../config/app-config'
import { windowsWebContentsSend } from './browser-windows.js'
import { BrowserWindow } from 'electron'

// 为ES模块提供__dirname和__filename
// const __filename = fileURLToPath(import.meta.url)
// const __dirname_local = dirname(__filename)
const windows = BrowserWindow.getAllWindows()

class HlsHttpServer {
  constructor() {
    this.server = null
    this.defaultPort = global.appConfig.httpServerConfig.defaultPort // 默认端口
    this.isServerRunning = false // 添加运行状态标志
    this.outputDir = join(
      global.appConfig.workspacePath,
      global.appConfig.rtsp2hlsConfig.hls.outputDir
    )
  }

  // 启动HLS文件服务器
  start(port = this.defaultPort) {
    this.server = createServer((req, res) => {
      this.handleRequest(req, res)
    })

    this.server.listen(port, () => {
      console.log(`HLS文件服务器已启动，监听端口: ${port}`)
      windowsWebContentsSend('addLog', `[INFO] HLS文件服务器已启动，监听端口: ${port}`)
      this.isServerRunning = true // 设置为运行状态
      global.appConfig.httpServerConfig.runningPort = port // 更新运行时端口配置
    })

    this.server.on('error', (error) => {
      console.error('HLS服务器错误:', error)
      this.isServerRunning = false // 设置为非运行状态
      global.appConfig.httpServerConfig.runningPort = 0 // 更新运行时端口配置为0
      // 如果端口被占用，尝试其他端口
      if (error.code === 'EADDRINUSE') {
        console.log(`端口 ${port} 被占用，尝试端口 ${port + 1}`)
        this.start(port + 1)
      }
    })
  }

  // 检查服务器是否运行
  isRunning() {
    return this.isServerRunning && this.server !== null
  }

  // 处理HTTP请求
  handleRequest(req, res) {
    const url = req.url
    console.log(`HLS服务器收到请求: ${url}`)

    // 请求源
    const referer = req.headers['referer'] || ''
    console.log(`请求来源: ${referer}`)

    // 处理HLS文件请求
    if (url.startsWith('/hls/')) {
      const filename = url.substring(5) // 去掉 '/hls/'
      // const filePath = join(__dirname_local, 'hls_output', filename)
      const filePath = join(this.outputDir, filename)
      console.log(`尝试访问文件: ${filePath}`)

      windows.forEach((window) => {
        window.webContents.send('addLog', `[INFO] 尝试访问文件: ${filePath}`)
      })

      // 检查文件是否存在
      fs.access(filePath, fs.constants.F_OK, (err) => {
        if (err) {
          console.error(`文件不存在: ${filePath}`)
          res.writeHead(404, { 'Content-Type': 'text/plain' })
          res.end(`Not Found: ${filePath}`)
          return
        }

        this.serveHlsFile(filePath, res)
      })
    } else {
      // 返回404
      console.log(`未处理的请求路径: ${url}`)
      res.writeHead(404, { 'Content-Type': 'text/plain' })
      res.end('Must start with /hls/ .')
    }
  }

  // 获取MIME类型（简化版本，避免依赖mime-types）
  getMimeType(filePath) {
    const ext = filePath.split('.').pop().toLowerCase() // 获取文件扩展名
    const mimeTypes = {
      m3u8: 'application/vnd.apple.mpegurl',
      ts: 'video/mp2t',
      mp4: 'video/mp4',
      js: 'application/javascript',
      css: 'text/css',
      html: 'text/html',
      txt: 'text/plain'
    }
    return mimeTypes[ext] || 'application/octet-stream'
  }

  // 提供HLS文件
  serveHlsFile(filePath, res) {
    fs.access(filePath, fs.constants.F_OK, (err) => {
      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/plain' })
        res.end('File Not Found')
        return
      }

      const mimeType = this.getMimeType(filePath)
      const stat = fs.statSync(filePath)

      res.writeHead(200, {
        'Content-Type': mimeType,
        'Content-Length': stat.size,
        'Access-Control-Allow-Origin': '*', // 允许跨域
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
      })

      const readStream = fs.createReadStream(filePath)
      readStream.pipe(res)
    })
  }

  // 停止服务器
  stop() {
    if (this.server) {
      this.server.close(() => {
        console.log('HLS文件服务器已停止')
        this.isServerRunning = false // 设置为非运行状态
      })
    }
  }
}

export { HlsHttpServer }
